package cn.shentianlan.service.impl;

import cn.shentianlan.dao.DeviceDataDao;
import cn.shentianlan.domain.DeviceData;
import cn.shentianlan.domain.DeviceDataForValue;
import cn.shentianlan.service.DeviceDataService;
import cn.shentianlan.utils.JsonUtils;
import cn.shentianlan.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DeviceDataServiceImpl implements DeviceDataService {

    @Resource
    private DeviceDataDao deviceDataDao;

    @Resource
    private RedisUtil redisUtil;


    @Override
    public void addDeviceData(String id,DeviceData deviceData) throws JsonProcessingException {
        System.out.println("addDeviceData:"+deviceData);
        DeviceDataForValue deviceDataForValue = new DeviceDataForValue();
        deviceDataForValue.setId(id);
        deviceDataForValue.setGd_dev_CH4(deviceData.getGd_dev_CH4());
        deviceDataForValue.setGd_dev_H2S(deviceData.getGd_dev_H2S());
        deviceDataForValue.setGd_dev_O2(deviceData.getGd_dev_O2());
        deviceDataForValue.setGd_dev_Rh(deviceData.getGd_dev_Rh());
        deviceDataForValue.setGd_dev_TEMP(deviceData.getGd_dev_TEMP());
        deviceDataForValue.setGd_dev_time(deviceData.getGd_dev_time());

        deviceDataDao.insertDeviceData(deviceDataForValue);
    }

    @Override
    public String getDeviceData(String id, String date) throws JsonProcessingException {
        //从Redis中没有查询到数据，到MySQL数据库中进行查询，并将查询到的数据存入Redis数据库中
        String key = id+":"+date;
        try{
            String range = redisUtil.range(key);
            if (range != null && range.length()>0){
                return range;
            }else {
                List<DeviceData> deviceDataList = deviceDataDao.queryDeviceDataByIdAndDate(id, date);
                redisUtil.push(key,deviceDataList);
                return JsonUtils.ObjectToString(deviceDataList);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            List<DeviceData> deviceDataList = deviceDataDao.queryDeviceDataByIdAndDate(id, date);
            return JsonUtils.ObjectToString(deviceDataList);
        }

    }

    @Override
    public List<String> getDeviceDate(String id) {
        return deviceDataDao.getDeviceDate(id);
    }

    //判断是否存在该表
    @Override
    public Object getTable(String id) {
        return deviceDataDao.getTable(id);
    }

    //建表
    @Override
    public void createTable(String id) {
        deviceDataDao.createTable(id);
    }
}
